package com.bawei.module_inspection.ui

import com.bawei.lib_common.base.BaseViewModel
import com.bawei.lib_common.base.state.Failed
import com.bawei.lib_common.base.state.Loading
import com.bawei.lib_common.base.state.RequestEvent
import com.bawei.lib_common.base.state.Success
import com.bawei.module_inspection.model.PatrolModelItem
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import javax.inject.Inject


@HiltViewModel
class InspectionViewModel @Inject constructor(private val repository: InspectionRepository) : BaseViewModel() {

    var mInspectionListData = listOf<PatrolModelItem>()

    val mInspection_ = MutableStateFlow<RequestEvent>(Loading)
    val mInspectionState = mInspection_.asStateFlow()

    fun getInspection() {
        execute(
            action = repository.getInspection(),
            onStart = {
                mInspection_.value = Loading
            },
            onError = {
                mInspection_.value = Failed(it)
            },
            onFinish = {
                mInspectionListData = it.data.reversed()
                mInspection_.value = Success
            }
        )
    }

    fun postInspection(patrolModelItem: PatrolModelItem) {
        execute(
            action = repository.postInspection(patrolModelItem),
            onStart = {
                mInspection_.value = Loading
            },
            onError = {
                mInspection_.value = Failed(it)
            },
            onFinish = {
                getInspection()
                mInspection_.value = Success
            },
        )
    }

    fun getInspectionDetail(id: Int) {
        execute(
            action = repository.getInspectionDetail(id),
            onStart = {
                mInspection_.value = Loading
            },
            onError = {
                mInspection_.value = Failed(it)
            },
            onFinish = {
                mInspection_.value = Success
            },
        )
    }


}